const fs = require('fs');
const path = require('path');
const util = require('util');
const poppler = require('pdf-poppler');
const config = require('./config');

const readdir = util.promisify(fs.readdir);
const stat = util.promisify(fs.stat);
const mkdir = util.promisify(fs.mkdir);
const copyFile = util.promisify(fs.copyFile);
const writeFile = util.promisify(fs.writeFile);

class PdfConverter {
  constructor() {
    this.namingRules = config.namingRules;
    this.logEntries = [];
  }

  // 初始化日志
  initLog() {
    this.logEntries = [];
    this.logEntries.push(`转换开始时间: ${new Date().toLocaleString()}`);
  }

  // 添加日志条目
  addLogEntry(message) {
    const entry = `[${new Date().toLocaleTimeString()}] ${message}`;
    this.logEntries.push(entry);
    console.log(entry);
  }

  // 保存日志到文件
  async saveLog() {
    this.logEntries.push(`\n转换结束时间: ${new Date().toLocaleString()}`);
    try {
      await writeFile(config.logFile, this.logEntries.join('\n'));
    } catch (error) {
      console.error('保存日志失败:', error);
    }
  }

  // 提取PDF文件的关键部分用于匹配命名规则
  extractKeyFromFilename(filename) {
    // 移除数字前缀和可能的权利人姓名后缀
    const baseName = path.basename(filename, path.extname(filename))
      .replace(/^\d+/, '') // 移除开头的数字
      .replace(/-.*$/, ''); // 移除短横线后的权利人姓名
    
    return baseName;
  }

  // 获取新文件名
  getNewFilename(originalName, pageNum = null) {
    let key = this.extractKeyFromFilename(originalName);
    let namingRuleKeys = Object.keys(this.namingRules)
    let prefixKey = namingRuleKeys.find(k => key.includes(k))
    let prefix = originalName.replace('.pdf', '') + '_';
    if(prefixKey) {
      prefix = this.namingRules[prefixKey]
    }
    if (pageNum !== null) {
      return `${prefix}${pageNum}.jpg`;
    }
    return `${prefix}.jpg`;
  }

  // 转换单个PDF文件
  async convertPdf(pdfPath, targetDir) {
    const pdfName = path.basename(pdfPath);
    const opts = {
      format: 'jpeg',
      out_dir: targetDir,
      out_prefix: 'temp_', // 临时前缀，后面会重命名
      page: null, // 所有页
      scale: config.resolution
    };

    try {
      await poppler.convert(pdfPath, opts);
      this.addLogEntry(`✅ PDF转换成功: ${pdfName}`);

      // 重命名生成的文件
      const files = await readdir(targetDir);
      const pdfFiles = files.filter(file => 
        file.startsWith('temp_') && file.endsWith('.jpg')
      );

      for (let i = 0; i < pdfFiles.length; i++) {
        const oldPath = path.join(targetDir, pdfFiles[i]);
        const newName = this.getNewFilename(pdfName, i + 1);
        const newPath = path.join(targetDir, newName);
        
        fs.renameSync(oldPath, newPath);
      }

      return pdfFiles.length;
    } catch (error) {
      this.addLogEntry(`❌ PDF转换失败: ${pdfName} - ${error.message}`);
      return 0;
    }
  }

  /**
   * 递归处理文件夹及其所有子文件夹
   * @param {string} sourceFolder 源文件夹路径
   * @param {string} targetRoot 目标根文件夹路径
   * @param {string} relativePath 当前处理的相对路径
   * @returns {Promise<{pdfCount: number, imageCount: number, pageCount: number}>} 处理结果
   */
  async processDirectory(sourceFolder, targetRoot, relativePath = '') {
    const targetFolder = path.join(targetRoot, relativePath);
    
    // 确保目标文件夹存在
    if (!fs.existsSync(targetFolder)) {
      await mkdir(targetFolder, { recursive: true });
    }

    const items = await readdir(sourceFolder);
    let pdfCount = 0;
    let imageCount = 0;
    let pageCount = 0;

    for (const item of items) {
      const sourcePath = path.join(sourceFolder, item);
      const stats = await stat(sourcePath);

      if (stats.isDirectory()) {
        // 递归处理子文件夹
        this.addLogEntry(`\n📁 处理文件夹: ${item}`);
        const subRelativePath = path.join(relativePath, item);
        const result = await this.processDirectory(sourcePath, targetRoot, subRelativePath);
        pdfCount += result.pdfCount;
        imageCount += result.imageCount;
        pageCount += result.pageCount;
      } else {
        const ext = path.extname(item).toLowerCase();
        const targetPath = path.join(targetFolder, item);
        
        // 处理PDF文件
        if (ext === '.pdf') {
          const pages = await this.convertPdf(sourcePath, targetFolder);
          pdfCount++;
          pageCount += pages;
        } 
        // 处理图片文件（直接复制）
        else if (['.jpg', '.jpeg', '.png'].includes(ext)) {
          await copyFile(sourcePath, targetPath);
          imageCount++;
          this.addLogEntry(`📸 复制图片: ${path.join(relativePath, item)}`);
        }
      }
    }

    return { pdfCount, imageCount, pageCount };
  }

  /**
   * 批量处理文件夹（支持嵌套结构）
   * @param {string} sourceRoot 源根文件夹路径
   * @param {string} targetRoot 目标根文件夹路径
   * @returns {Promise<{success: boolean, totalFolders?: number, totalPdfs?: number, totalImages?: number, totalPages?: number, error?: string}>} 处理结果
   */
  async batchConvert(sourceRoot, targetRoot) {
    this.initLog();
    
    try {
      this.addLogEntry('='.repeat(60));
      this.addLogEntry(`开始批量处理: ${sourceRoot}`);
      this.addLogEntry('='.repeat(60));

      // 处理根文件夹及其所有子文件夹
      const result = await this.processDirectory(sourceRoot, targetRoot);
      
      this.addLogEntry('\n' + '='.repeat(60));
      this.addLogEntry('批量处理完成!');
      this.addLogEntry('='.repeat(60));
      this.addLogEntry(`转换PDF文件: ${result.pdfCount}个 (共${result.pageCount}页)`);
      this.addLogEntry(`复制图片文件: ${result.imageCount}个`);
      this.addLogEntry('='.repeat(60));
      
      await this.saveLog();
      
      return {
        success: true,
        totalPdfs: result.pdfCount,
        totalImages: result.imageCount,
        totalPages: result.pageCount
      };
    } catch (error) {
      this.addLogEntry(`❌ 批量处理失败: ${error.message}`);
      await this.saveLog();
      return { success: false, error: error.message };
    }
  }
}

module.exports = PdfConverter;